package Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//TCP实现的回显服务器
public class TcpEchoServer {
    //1.创建一个ServerSocket对象
    private ServerSocket serverSocket = null;
    private ExecutorService executor = Executors.newCachedThreadPool();//不指定线程池的大小，实现按需创建线程
    //2.编写构造方法传入服务器的端口号
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    //3.编写start方法用于接收系统内核的连接
    private void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //接收连接
            Socket clientSocket = serverSocket.accept();//接收到系统内核中的客户端连接
            //处理接收到的用户连接
            //多个客户端，需要多个线程来执行，否则会出现其他客户端请求来的时候服务器处理不了
            //还可以通过线程池的方式来创建线程，避免频繁的线程创建与销毁
            //线程池按需创建线程
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            //创建多线程完成多个客户端的任务
//            Thread t = new Thread(()->{
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//            t.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线了\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //接收请求
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //读取接收到的请求
            while (true){
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                //看我护短发过来文本数据，同时以换行这种空白符作为分割
                String request = scanner.next();
                //处理请求，给出响应
                String response = process(request);
                //将响应写入到InputStream中，发送给客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s rep:%s\n",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
            }
        }finally {
            clientSocket.close();//关闭文件，避免出现内存泄露
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
